#!/bin/bash

# Docker网络问题诊断和修复脚本
echo "🔧 Docker网络问题诊断和修复"
echo "=========================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 1. 诊断Docker状态
diagnose_docker() {
    log_info "诊断Docker状态..."
    
    # 检查Docker是否运行
    if ! docker info >/dev/null 2>&1; then
        log_error "Docker未运行或无权限访问"
        log_info "请启动Docker Desktop或使用sudo"
        return 1
    fi
    
    # 检查Docker版本
    DOCKER_VERSION=$(docker --version)
    log_success "Docker运行正常: $DOCKER_VERSION"
    
    # 检查网络连接
    log_info "测试网络连接..."
    if ping -c 1 registry-1.docker.io >/dev/null 2>&1; then
        log_success "可以连接到Docker Hub"
    else
        log_warning "无法连接到Docker Hub，可能需要配置代理或镜像源"
    fi
    
    return 0
}

# 2. 配置Docker镜像加速器
configure_docker_mirrors() {
    log_info "配置Docker镜像加速器..."
    
    # 检测操作系统
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        log_info "检测到macOS系统"
        log_warning "请手动配置Docker Desktop镜像源："
        echo "1. 打开Docker Desktop"
        echo "2. 点击设置图标 ⚙️"
        echo "3. 选择 Docker Engine"
        echo "4. 在JSON配置中添加镜像源："
        echo '{'
        echo '  "registry-mirrors": ['
        echo '    "https://docker.mirrors.ustc.edu.cn",'
        echo '    "https://hub-mirror.c.163.com"'
        echo '  ]'
        echo '}'
        echo "5. 点击 Apply & Restart"
        echo ""
        read -p "配置完成后按回车继续..." -r
        
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Linux
        log_info "检测到Linux系统"
        DAEMON_JSON="/etc/docker/daemon.json"
        
        if [ -f "$DAEMON_JSON" ]; then
            sudo cp "$DAEMON_JSON" "$DAEMON_JSON.backup.$(date +%Y%m%d_%H%M%S)"
        fi
        
        sudo tee "$DAEMON_JSON" > /dev/null <<EOF
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://mirror.baidubce.com"
  ]
}
EOF
        
        sudo systemctl daemon-reload
        sudo systemctl restart docker
        log_success "Docker镜像源配置完成"
    fi
}

# 3. 测试镜像拉取
test_image_pull() {
    log_info "测试镜像拉取..."
    
    # 测试镜像列表（按优先级）
    local test_images=(
        "hello-world:latest"
        "alpine:latest"
        "nginx:alpine"
    )
    
    for image in "${test_images[@]}"; do
        log_info "测试拉取镜像: $image"
        if timeout 60 docker pull "$image" >/dev/null 2>&1; then
            log_success "成功拉取镜像: $image"
            docker rmi "$image" >/dev/null 2>&1  # 清理测试镜像
            return 0
        else
            log_warning "拉取失败: $image"
        fi
    done
    
    log_error "所有测试镜像拉取失败"
    return 1
}

# 4. 尝试国内镜像源
try_chinese_mirrors() {
    log_info "尝试使用国内镜像源..."
    
    # 国内镜像源列表
    local mirrors=(
        "registry.cn-hangzhou.aliyuncs.com"
        "registry.cn-beijing.aliyuncs.com"
        "registry.cn-shenzhen.aliyuncs.com"
        "dockerhub.azk8s.cn"
        "reg-mirror.qiniu.com"
    )
    
    for mirror in "${mirrors[@]}"; do
        log_info "测试镜像源: $mirror"
        # 测试拉取一个小镜像
        if timeout 30 docker pull "$mirror/library/hello-world:latest" >/dev/null 2>&1; then
            log_success "镜像源可用: $mirror"
            docker rmi "$mirror/library/hello-world:latest" >/dev/null 2>&1
            echo "$mirror" > .working_mirror
            return 0
        fi
    done
    
    log_error "所有国内镜像源都无法访问"
    return 1
}

# 5. 创建优化的Docker Compose文件
create_optimized_compose() {
    log_info "创建优化的Docker Compose配置..."
    
    # 选择工作的镜像源
    local mirror=""
    if [ -f .working_mirror ]; then
        mirror=$(cat .working_mirror)
        log_info "使用镜像源: $mirror"
    fi
    
    # 创建优化的配置文件
    cat > docker-compose.optimized.yml << EOF
version: '3.8'

services:
  # MongoDB 数据库
  mongodb:
    image: ${mirror:+$mirror/library/}mongo:6
    container_name: devops-mongodb
    restart: unless-stopped
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: admin123
    volumes:
      - mongodb_data:/data/db
    networks:
      - devops-network
    healthcheck:
      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ismaster')"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 40s

  # Redis 缓存
  redis:
    image: ${mirror:+$mirror/library/}redis:7-alpine
    container_name: devops-redis
    restart: unless-stopped
    ports:
      - "6379:6379"
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
    networks:
      - devops-network
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 30s
      timeout: 3s
      retries: 5

  # Prometheus 监控
  prometheus:
    image: ${mirror:+$mirror/}prom/prometheus:v2.45.0
    container_name: devops-prometheus
    restart: unless-stopped
    ports:
      - "9090:9090"
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--storage.tsdb.retention.time=15d'
      - '--web.enable-lifecycle'
    volumes:
      - ./monitoring/prometheus-simple.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    networks:
      - devops-network
    healthcheck:
      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:9090/-/healthy"]
      interval: 30s
      timeout: 5s
      retries: 5

networks:
  devops-network:
    driver: bridge

volumes:
  mongodb_data:
  redis_data:
  prometheus_data:
EOF

    log_success "优化的Docker Compose配置已创建"
}

# 6. 创建简化的Prometheus配置
create_simple_prometheus_config() {
    log_info "创建简化的Prometheus配置..."
    
    mkdir -p monitoring
    cat > monitoring/prometheus-simple.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'devops-backend'
    static_configs:
      - targets: ['host.docker.internal:8000']
    scrape_interval: 30s
    metrics_path: /metrics
EOF

    log_success "简化的Prometheus配置已创建"
}

# 7. 启动优化后的服务
start_optimized_services() {
    log_info "启动优化后的服务..."
    
    # 拉取镜像
    log_info "拉取所需镜像..."
    if ! docker-compose -f docker-compose.optimized.yml pull; then
        log_error "镜像拉取失败"
        return 1
    fi
    
    # 启动服务
    log_info "启动服务..."
    if ! docker-compose -f docker-compose.optimized.yml up -d; then
        log_error "服务启动失败"
        return 1
    fi
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 30
    
    # 检查服务状态
    local services=("mongodb" "redis" "prometheus")
    for service in "${services[@]}"; do
        if docker-compose -f docker-compose.optimized.yml ps "$service" | grep -q "Up"; then
            log_success "$service 启动成功"
        else
            log_warning "$service 可能启动失败"
        fi
    done
    
    return 0
}

# 8. 验证服务
verify_services() {
    log_info "验证服务状态..."
    
    # 验证MongoDB
    if docker exec devops-mongodb mongosh --eval "db.adminCommand('ismaster')" --quiet >/dev/null 2>&1; then
        log_success "MongoDB 运行正常"
    else
        log_warning "MongoDB 连接失败"
    fi
    
    # 验证Redis
    if docker exec devops-redis redis-cli ping >/dev/null 2>&1; then
        log_success "Redis 运行正常"
    else
        log_warning "Redis 连接失败"
    fi
    
    # 验证Prometheus
    if curl -f -s http://localhost:9090/-/healthy >/dev/null 2>&1; then
        log_success "Prometheus 运行正常"
    else
        log_warning "Prometheus 连接失败"
    fi
}

# 主函数
main() {
    echo ""
    log_info "开始Docker网络问题修复..."
    echo ""
    
    # 诊断
    if ! diagnose_docker; then
        exit 1
    fi
    
    # 配置镜像源
    configure_docker_mirrors
    
    # 测试拉取
    if ! test_image_pull; then
        log_warning "直接拉取失败，尝试国内镜像源..."
        if ! try_chinese_mirrors; then
            log_error "所有镜像源都无法访问，请检查网络连接"
            exit 1
        fi
    fi
    
    # 创建优化配置
    create_optimized_compose
    create_simple_prometheus_config
    
    # 启动服务
    if start_optimized_services; then
        verify_services
        
        echo ""
        log_success "Docker服务启动完成！"
        echo "=========================="
        echo ""
        echo "📊 Prometheus:  http://localhost:9090"
        echo "🗄️  MongoDB:     mongodb://admin:admin123@localhost:27017"
        echo "📦 Redis:       redis://localhost:6379"
        echo ""
        echo "📋 后续步骤:"
        echo "   cd backend && npm install && npm run dev"
        echo "   cd frontend && npm install && npm run dev"
        echo ""
        echo "🛑 停止服务:"
        echo "   docker-compose -f docker-compose.optimized.yml down"
        echo ""
        
    else
        log_error "服务启动失败"
        exit 1
    fi
}

# 执行
main "$@"